﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.DataModel;

namespace Giaiphongmatbang
{
    public partial class createDuan : System.Web.UI.Page
    {
        QLGPMBEntities db = new QLGPMBEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"] != null)
                {
                    if (!new UserRolesRepository().CheckRoles((User)Session["User"], (int)Utility.Enum.Roles.CreateProject))
                    {
                        Response.Redirect("/duan.aspx");
                    }
                }
                Title = ":: Tạo mới dự án giải phóng mặt bằng ::";
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            
            string ProjectName = txtProjectName.Text.Trim();
            string Investor = txtInvestor.Text.Trim();
            txtProjectName.Text = string.Empty;
            txtInvestor.Text = string.Empty;
            if (string.IsNullOrEmpty(ProjectName) || string.IsNullOrEmpty(Investor))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Hãy nhập đầy đủ thông tin cho dự án!');", true);
                return;
            }
            bool isPublic = chkPublic.Checked;
            bool isCompleted = chkCompleted.Checked;
            var date = DateTime.Now;
            DateTime.TryParse(txtCreatedDate.Text,out date);
            Project project = new Project
            {
                ProjectName = ProjectName,
                Investor = Investor,
                CreatedDate = date,
                isCompleted = isCompleted,
                isPublic = isPublic
            };
            db.AddToProjects(project);
            db.SaveChanges();
            string[] split = new string[] { "$--$" };
            string[] separator = new string[] { "|$--$|" };
            string[] arrInvestor = hdfValue.Value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrInvestor)
            {
                string[] value = item.Split(split, StringSplitOptions.None);
                Managment managment = new Managment
                {
                    Project = db.Projects.FirstOrDefault(p=>p.CreatedDate == date),
                    FullName = value[0],
                    Order = value[1],
                    Representative = value[2]
                };
                db.SaveChanges();
            }

            Response.Redirect("/duan.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/duan.aspx");
        }
    }
}